package com.brotherly.util.downloader;

import java.io.File;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import android.content.Context;

import com.brotherly.framework.event.EventService;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.util.InternetResourceCache;
import com.umeng.analytics.MobclickAgent;

/**
 * 
 * @author robin
 * @date 2013-6-21
 */
public class DownLoaderUtil
{
    private Context context;
    private EventService eventService;

    // 下载路径和类型
    public static final String BASEURL = "http://202.102.39.26:80/strategy/api/games/blob?key=package";

    // SD卡目录下
    // public static final String BASESAVEFILE_PATH =
    // "/mnt/sdcard/gamecyclone/package";
    public static final String APK_PATH = InternetResourceCache.getCacheDir() + "apk/";
    public static final String IMAGE_PATH = InternetResourceCache.getCacheDir() + "image/";

    // 下载进度
    // private static Map<String, Downloader> downloaders = new HashMap<String,
    // Downloader>();
    private Downloader currentDownLoader;
    private Queue<Downloader> downloaders = new LinkedBlockingQueue<Downloader>();

    public static final String Activity_Event_FileDownload_Info = "Activity_Event_FileDownload_Info";
    public static final String Activity_Event_FileDownload_Pause = "Activity_Event_FileDownload_Pause";
    public static final String Activity_Event_FileDownload_Start = "Activity_Event_FileDownload_Start";

    private static DownLoaderUtil dlUtil;

    private DownLoaderUtil()
    {

    }

    public synchronized static DownLoaderUtil getInstence(Context context)
    {
        if (dlUtil == null)
        {
            dlUtil = new DownLoaderUtil();
            dlUtil.context = context;
            dlUtil.eventService = (EventService) ServiceManager.getInstance().getService(ServiceManager.EVENT_SERVICE);
        }

        File file = new File(InternetResourceCache.getCacheDir());
        if (!file.exists())
        {
            file.mkdirs();
        }
        file = new File(APK_PATH);
        if (!file.exists())
        {
            file.mkdirs();
        }
        file = new File(IMAGE_PATH);
        if (!file.exists())
        {
            file.mkdirs();
        }

        return dlUtil;
    }

    public synchronized String startDownLoader(int id, String fileName, int state, int fileSize)
    {
        String localfile = new StringBuffer(DownLoaderUtil.APK_PATH).append(fileName).append(".apk").toString();
        String url = new StringBuffer(BASEURL).append("&gameref=").append(id).toString();
        startDownLoader(url, localfile, fileName, state, fileSize);
        return url;
    }

    private void startDownLoader(String url, String localfile, String fileName, int state, int fileSize)
    {
        // 设置下载线程数为1，在手机上没必要多线程
        int threadcount = 1;
        if (!this.checkNotDownLoadering())
        {
            Downloader dl = new Downloader(url, localfile, fileName, threadcount, this.context, this.eventService);
            dl.setFileSize(fileSize);
            downloaders.offer(dl);
        }
        else
        {
            // Log.d("DownLoader", downloaders.toString());
            this.currentDownLoader = new Downloader(url, localfile, fileName, threadcount, this.context, eventService);
            this.currentDownLoader.reset();
            this.currentDownLoader.getDownloaderInfors(fileSize);
            this.currentDownLoader.download();
            MobclickAgent.onEvent(context, "Downloader");
        }
    }

    public synchronized void pauseDownload()
    {
        this.currentDownLoader.pause();
    }

    public synchronized void stopDownload(String url)
    {
        this.currentDownLoader = null;
        DBUtil dbUtil = DBUtil.getInstance();
        dbUtil.updateComplete(url);
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    Thread.sleep(5000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                nextDownload();
            }
        }).start();
    }

    public void cancelWait(int id)
    {
        String url = new StringBuffer(BASEURL).append("&gameref=").append(id).toString();

        Object[] dls = (Object[]) downloaders.toArray();
        this.downloaders.clear();
        for (int i = 0; i < dls.length; i++)
        {
            Downloader dl = (Downloader) dls[i];
            if (!url.equals(dl.getUrl()))
            {
                this.downloaders.offer(dl);
            }
        }
        // Log.d("DownLoader", downloaders.toString());
    }

    public synchronized void nextDownload()
    {
        if (!checkNotDownLoadering())
        {
            return;
        }
        if (this.currentDownLoader != null)
        {
            if (this.downloaders.size() != 0)
            {
                this.downloaders.offer(this.currentDownLoader);
            } else
            {
                this.downloaders.offer(this.currentDownLoader);
            }
        }

        this.currentDownLoader = this.downloaders.poll();
        if (this.currentDownLoader != null)
        {
            if (this.currentDownLoader.getState() != Downloader.PAUSE)
            {
                this.currentDownLoader.getDownloaderInfors(0);
                this.currentDownLoader.download();
            }
        }
    }

    public boolean checkNotDownLoadering()
    {
        if (this.currentDownLoader == null)
            return true;
        return this.currentDownLoader.getState() != Downloader.DOWNLOADING;
    }

    public boolean checkCurrentDownLoader(int id)
    {
        if (checkNotDownLoadering())
            return false;
        String url = new StringBuffer(BASEURL).append("&gameref=").append(id).toString();
        return this.currentDownLoader.getUrl().equals(url);
    }

    public boolean isDownLoaderWait(String url)
    {
        Object[] dls = (Object[]) downloaders.toArray();
        for (int i = 0; i < dls.length; i++)
        {
            Downloader dl = (Downloader) dls[i];
            if (url.equals(dl.getUrl()))
            {
                return true;
            }
        }
        return false;
    }

    public void clearAllDownLoader()
    {
        if (currentDownLoader != null)
        {
            currentDownLoader.pause();
            currentDownLoader.isStopForce = true;
        }
        downloaders.clear();
        DBUtil dbUtil = DBUtil.getInstance();
        dbUtil.deleteAll();
    }
}
